

import { GlobalVal } from "../global";
import { baseData } from "./init";
/**
 * @description 初始化
 */
export function run() {
  try {    
    // 自动退出登录
    autoLogout()
  } catch (error) {
    console.warn(error)
  }
}


export function login(username, password) {

  const usernameInput = baseData.mainIframeTopDocument.querySelector('#username');

  const passwordInput = baseData.mainIframeTopDocument.querySelector('#password');
  const loginBtn = baseData.mainIframeTopDocument.querySelector(`button[fieldid="login_btn"]`);
  usernameInput.value = username;
  passwordInput.value = password;
  setTimeout(() => {
    loginBtn.click();
  }, 1000);
}

// 通过dom获取react节点
function FindReact(dom) {
  if (!dom) {
    return;
  }
  let key = Object.keys(dom).find((key) =>
    key.startsWith('__reactInternalInstance$')
  );
  let internalInstance = dom[key];
  if (internalInstance == null) return null;

  if (internalInstance.return) {
    // react 16+
    return internalInstance._debugOwner
      ? internalInstance._debugOwner.stateNode
      : internalInstance.return.stateNode;
  } else {
    // react <16
    return internalInstance._currentElement._owner._instance;
  }
}






export function autoLogin() {
  setTimeout(() => {
    try {
      let name = GetQueryString('name') 
      let pwd = GetQueryString('pwd') 
      if (name) {
        login(name, pwd)
      }
      
    } catch (error) {
      console.warn(error)
    }
  }, 1000);
}


function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}


export function autoLogout () {
  let timer = setInterval(() => {
    let p = baseData.mainIframeTopDocument.querySelector('.prompt-content')
    if (p && document.title === '首页') {
      clearInterval(timer)
      baseData.mainIframeTopDocument.querySelector('.button-primary').click()
    }
  }, 1000);
}